package com.newgrand.annexserver.filter;

import com.newgrand.annexcommon.model.Result;
import com.newgrand.annexcommon.utils.JsonUtil;
import com.newgrand.annexcommon.utils.ResultUtil;
import com.newgrand.annexserver.beans.Dbconfig;
import com.newgrand.annexserver.exception.NoDataSourceException;
import com.newgrand.annexserver.service.DbconfigService;
import com.newgrand.annexserver.storage.StorageContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author ：minyang
 * @date ：Created in 2019/9/8 15:43
 */
public class DataSourceFilter implements Filter {


    DbconfigService dbconfigService;

    public DataSourceFilter(DbconfigService dbconfigService) {
        this.dbconfigService = dbconfigService;
    }

    /**
     * 容器加载的时候调用
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init dataSourceFilter");
    }


    /**
     * 请求被拦截的时候进行调用
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, RuntimeException {
        System.out.println("doFilter dataSourceFilter");

        HttpServletRequest req = (HttpServletRequest) servletRequest;
//        HttpServletResponse resp = (HttpServletResponse) servletResponse;
//        String username = req.getParameter("username");
        String dbtoken = req.getHeader("dbtoken");
        if (dbtoken == null || dbtoken.trim() == "") {
            handleException(servletResponse, "dbtoken为空");
            return;
        }
        Dbconfig dbconfig = dbconfigService.getDBConfigByDbToken(dbtoken);
        if (dbconfig == null) {
            handleException(servletResponse, "dbtoken为空");
            return;
        }
        StorageContextHolder.setDbConfig(dbconfig);
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("doFilter dataSourceFilter success");
    }

    /**
     * 容器被销毁的时候被调用
     */
    @Override
    public void destroy() {
        System.out.println("destroy dataSourceFilter");
    }

    private void handleException(ServletResponse servletResponse, String msg) throws IOException {
        String result = JsonUtil.beanToJsonString(ResultUtil.fail(msg));
        ServletOutputStream out = servletResponse.getOutputStream();
        out.write(result.getBytes());
        out.flush();
    }

}
